﻿using System;

using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace IFD2
{
    public partial class QueryConnection : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblError.Text = "";
            if (!IsPostBack)
            {
                if (Session["ACL"].ToString().IndexOf("SB4") < 0)
                {
                    Response.Redirect("unauthorized.aspx");
                }

                if (Session["FLT_DATE"] != null)
                    txtDate.Text = Convert.ToDateTime(Session["FLT_DATE"].ToString()).ToShortDateString();
                if (Session["ORI"] != null)
                    txtOriCity.Text = Session["ORI"].ToString();
                if (Session["DES"] != null)
                    txtDesCity.Text = Session["DES"].ToString();
            }
        }

        protected void lbtnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime.Parse(txtDate.Text);
            }
            catch
            {
                lblError.Text = "Invalid date format!";
                return;
            }
            //if (Application["DEBUG"].ToString() == "0")
            //{ 
                if (Session["CHK_CODE"] == null)
                {
                    lblError.Text = "Retry please.";
                    txtCheckCode.Text = "";
                    return;
                }
                if (txtCheckCode.Text.ToLower() != Session["CHK_CODE"].ToString())
                {
                    lblError.Text = "Wrong check code!";
                    txtCheckCode.Text = "";
                    return;
                }
            //}
            Session["CHK_CODE"] = ((char)10).ToString();// "K|DaI*K3^242L_JSD";
            txtCheckCode.Text = "";
            //Random rd = new Random();
            //Image1.ImageUrl = "img_chk.ashx?" + rd.Next().ToString();

            txtOriCity.Text = txtOriCity.Text.Trim().ToUpper();
            txtDesCity.Text = txtDesCity.Text.Trim().ToUpper();

            Session["FLT_DATE"] = txtDate.Text;
            Session["ORI"] = txtOriCity.Text;
            Session["DES"] = txtDesCity.Text;

            //string[] oriArray, desArray, distanceArray;
            //string ori_buf, des_buf, distance_buf;
            string out_buf;
            string[] routes_array, seg_array,stop_array;
            StringBuilder sb = new StringBuilder();
            int /*count,*/ ret_code;
            long total = 0;
            SqlCommand cmd = new SqlCommand();
            try
            {
                cmd.CommandText = "bll_query_get_transfer_plan2";
                SqlParameter para = cmd.Parameters.AddWithValue("@ori_city", txtOriCity.Text);
                para = cmd.Parameters.AddWithValue("@des_city", txtDesCity.Text);
                para = cmd.Parameters.AddWithValue("@flt_date", txtDate.Text);
                para = cmd.Parameters.AddWithValue("@airline", "*");
                //para = cmd.Parameters.AddWithValue("@ori_trans_times", lstTransTimes.SelectedValue);
                //para = cmd.Parameters.AddWithValue("@trans_times", lstTransTimes.SelectedValue);
                para = cmd.Parameters.AddWithValue("@max_trans_times", lstTransTimes.SelectedValue);
                para = cmd.Parameters.AddWithValue("@user_airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@office", Session["OFFICE"].ToString());
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());
                //para = cmd.Parameters.Add("@ori_buf", SqlDbType.VarChar);
                //para.Direction = ParameterDirection.Output;
                //para.Size = 1000;
                //SqlParameter para2 = cmd.Parameters.Add("@des_buf", SqlDbType.VarChar);
                //para2.Direction = ParameterDirection.Output;
                //para2.Size = 1000;
                //SqlParameter para3 = cmd.Parameters.Add("@distance_buf", SqlDbType.VarChar);
                //para3.Direction = ParameterDirection.Output;
                //para3.Size = 1000;
                para = cmd.Parameters.Add("@out", SqlDbType.VarChar);
                para.Direction = ParameterDirection.Output;
                para.Size = 8000;
                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                {
                    //ori_buf = para.Value.ToString();
                    out_buf = para.Value.ToString();
                    
                    //des_buf = para2.Value.ToString();
                    //distance_buf = para3.Value.ToString();
                    //oriArray = ori_buf.Split(',');
                    //desArray = des_buf.Split(',');
                    //distanceArray = distance_buf.Split(',');
                    //count = oriArray.GetLength(0);
                    sb.Append("<p style='font-family:courier;font-weight:bold;'><br/>");
                    
                    //for (int i = count - 2; i >= 0; i--)//(int i =0; i<= count-2; i++)
                    //{
                    //    sb.Append(oriArray[i].Trim() + "-" + desArray[i].Trim() + "(" + distanceArray[i] + " km)");
                    //    total = total + long.Parse(distanceArray[i]);
                    //    if (desArray[i].IndexOf(txtDesCity.Text) == 0)
                    //    {
                    //        sb.Append(" = " + total.ToString() + " km<br/>");
                    //        total = 0;
                    //    }
                    //    else
                    //        sb.Append(";");
                    //}
                    if (out_buf.Length == 0)
                        sb.Append("No connection!");
                    else
                    {
                        routes_array = out_buf.Split('|');
                        for (int i = 0; i < routes_array.Length; i++)
                        {
                            if (routes_array[i] == "")
                                break;

                            seg_array = routes_array[i].Split(';');
                            if (seg_array.Length == 0)
                            {
                                sb.Append("Invalid routes buffer: " + routes_array[i] + " !<br/>");
                                continue;
                            }
                            total = 0;
                            for (int k = 0; k < seg_array.Length; k++)
                            {
                                if (seg_array[k] == "")
                                    break;
                                stop_array = seg_array[k].Split(',');
                                if (stop_array.Length != 3)
                                {
                                    sb.Append("Invalid segment buffer: " + seg_array[k] + " !<br/>");
                                    continue;
                                }
                                try
                                {
                                    total = total + Convert.ToInt32(stop_array[2]);
                                }
                                catch (Exception ex)
                                {
                                    sb.Append("Invalid distance: " + stop_array[2] + " !<br/>");
                                    break;
                                }
                                sb.Append(stop_array[0].TrimEnd() + "-" + stop_array[1].TrimEnd() + "(" + stop_array[2].Trim() + "),");
                            }
                            sb.Append("Total: " + total.ToString() + "km.<br/>");

                        }
                    }
                    sb.Append("</p>");
                    litOut.Text = sb.ToString();

                }
                else if (ret_code == 1)
                {
                    lblError.Text = "Illegal Transfer Times!";
                    litOut.Text = "";
                }
                //else if (ret_code == 2)
                //{
                //    lblError.Text = "Transfer plan not found!";
                //    litOut.Text = "";
                //}
                else
                    lblError.Text = "Error:" + ret_code.ToString();
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblError.Text = ex.Message;
                else
                    lblError.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
                return;
            }
        }
    }
}